package com.sun.juc.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadDemo02 {
    public static void main(String[] args) {
        sharRouse sharRouse = new sharRouse();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                sharRouse.print5(i);
            }},"AA").start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                sharRouse.print10(i);
            }},"BB").start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                sharRouse.print15(i);
            }},"CC").start();
    }
}
class sharRouse{
    private int flag = 1;
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public void print5(int loop){
        lock.lock();
        try{
            while (flag != 1){
                c1.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "::第" + i + "::轮数" + loop );
            }
            flag = 2;
            c2.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void print10(int loop){
        lock.lock();
        try{
            while (flag != 2){
                c2.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "::第" + i + "::轮数" + loop );
            }
            flag = 3;
            c3.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void print15(int loop){
        lock.lock();
        try{
            while (flag != 3){
                c3.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName() + "::第" + i + "::轮数" + loop );
            }
            flag = 1;
            c1.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}